const { adoptPet, queryAdopt, adoptPetSuccess, removeAdopt } = require("../model/adoptModel")

module.exports = {
  // 领养
  adoptPet: async (ctx) => {
    const { pet_id, adopter_id } = ctx.request.body;
    // 通过id查询是否领养
    let query = await queryAdopt(pet_id);
    if (query.length !== 0) {
      if (query[0].pet_give_status == "true") {
        return ctx.body = {
          status: 205,
          msg: "已被领养"
        }
      }
    } else {
      return ctx.body = {
        status: 205,
        msg: "未找到该宠物"
      }
    }


    let res = await adoptPet(pet_id, adopter_id);

    if (res.affectedRows === 1) {
      ctx.body = {
        status: 200,
        msg: "领养成功"
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "领养失败"
      }
    }
  },
  // 成功领养
  adoptPetSuccess: async (ctx) => {
    const { pet_id } = ctx.request.body;

    // 通过id查询是否领养
    let query = await queryAdopt(pet_id);
    if (query.length !== 0) {
      if (query[0].pet_collar_status == "true") {
        return ctx.body = {
          status: 205,
          msg: "已领养成功"
        }
      }
    } else {
      return ctx.body = {
        status: 205,
        msg: "未找到该宠物"
      }
    }


    // 成功领养
    let res = await adoptPetSuccess(pet_id);
    if (res.affectedRows === 1) {
      ctx.body = {
        status: 200,
        msg: "成功"
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "失败"
      }
    }
  },
  // 取消领养
  removeAdopt: async (ctx) => {
    const { pet_id } = ctx.request.body;
    let query = await queryAdopt(pet_id);

    if (query.length !== 0) {
      if (query[0].pet_give_status == "false") {
        return ctx.body = {
          status: 205,
          msg: "该宠物暂未被领养"
        }
      }
    } else {
      return ctx.body = {
        status: 205,
        msg: "未找到该宠物信息"
      }
    }

    let res = await removeAdopt(pet_id);
    if (res.affectedRows === 1) {
      ctx.body = {
        status: 200,
        msg: "取消成功"
      }
    } else {
      ctx.body = {
        status: 205,
        msg: "取消失败"
      }
    }
  }
}